package com.chen.authorizationserver.Impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.chen.authorizationserver.entity.LoginUser;
import com.chen.authorizationserver.entity.TableUser;
import com.chen.authorizationserver.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;

/**
 * @author: cgd
 * @description:
 * @date: 2022/3/28 19:44
 * @version: 1.0
 */
@Service("UserDetailServiceImpl")
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        // 从数据库中取出用户信息
        TableUser tableUser = userMapper.selectOne(Wrappers.<TableUser>lambdaQuery().eq(TableUser::getAccount, s));

        // 判断用户是否存在
        if (tableUser == null) {
            throw new UsernameNotFoundException("账号或密码错误");
        }

        // 添加权限 todo 后期可添加权限
        SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ROLE_" + "USER");
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(authority);

        String encryptPassword = PasswordEncoderFactories.createDelegatingPasswordEncoder().encode(tableUser.getPassword());
        // 返回UserDetails实现类 todo 需自己实现缓存UserDetails
        return new LoginUser(tableUser.getAccount(), encryptPassword, authorities);
    }
}
